package com.webserver.core;

import com.webserver.controller.ArticleController;
import com.webserver.controller.ToolsController;
import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;

/**
 * 用来完成处理请求的环节
 */
public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response){
//        String path = request.getUri();//不再适用,因为当抽象路径含有参数时,参数的值是不固定的
        String path = request.getRequestURI();
        System.out.println("请求的抽象路径:"+path);
        //首先判断是否为请求一个业务处理
        if("/myweb/reg".equals(path)){

            UserController controller = new UserController();
            controller.reg(request,response);

        }else if("/myweb/login".equals(path)){

            UserController controller = new UserController();
            controller.login(request,response);

        }else if("/myweb/showAllUser".equals(path)){

            UserController controller = new UserController();
            controller.showAllUser(request,response);

        }else if("/myweb/writeArticle".equals(path)){

            ArticleController controller = new ArticleController();
            controller.writeArticle(request,response);

        }else if("/myweb/showAllArticle".equals(path)){

            ArticleController controller = new ArticleController();
            controller.showAllArticle(request,response);

        }else if("/myweb/createQR".equals(path)){

            ToolsController controller = new ToolsController();
            controller.createQR(request,response);

        }else if("/myweb/random.jpg".equals(path)){

            ToolsController controller = new ToolsController();
            controller.randomCode(request,response);

        }else {
            File file = new File("./webapps" + path);
            if (file.isFile()) {//请求的是一个存在的文件
                response.setContentFile(file);
            } else {
                response.setStatusCode(404);
                response.setStatusReason("Not Found");
                file = new File("./webapps/root/404.html");
                response.setContentFile(file);
            }
        }

        response.addHeader("Server","WebServer");
    }
}
